package com.example.batchdemo.service.Impl;

import com.example.batchdemo.mapper.UserMapper;
import com.example.batchdemo.pojo.User;
import com.example.batchdemo.service.UserService;
import com.example.batchdemo.util.HttpResult;
import com.example.batchdemo.util.PageUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @ClassName UserServiceImpl
 * @Author xiaojiang
 * @Date 2021/12/23 下午 16:02
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    UserMapper userMapper;
    @Autowired
    SqlSessionFactory sqlSessionFactory;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserOneByOne(List<User> users) {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        UserMapper um = session.getMapper(UserMapper.class);
        long startTime = System.currentTimeMillis();
        logger.info("开始时间 : {}", startTime);
        for (User user : users) {
            um.addUserOneByOne(user);
        }
        session.commit();
        long endTime = System.currentTimeMillis();
        logger.info("结束时间 : {}", startTime);
        logger.info("一条条插入 SQL 耗费时间 {}", (endTime - startTime));// 一条条插入 SQL 耗费时间 77719
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addByOneSQL(List<User> users) {
        long startTime = System.currentTimeMillis();
        userMapper.addByOneSQL(users);
        long endTime = System.currentTimeMillis();
        logger.info("合并成一条 SQL 插入耗费时间 {}", (endTime - startTime));//合并成一条 SQL 插入耗费时间 3591
    }

    @Override
    public HttpResult GetAll(Integer page, Integer pageSize) {
        int recordCount = userMapper.getUserCount();
        Map<String, Integer> stringIntegerMap = PageUtils.PageUtil(page, pageSize);
        List<User> list = userMapper.getUser(stringIntegerMap.get("pages"), stringIntegerMap.get("pageSizes"));


        return HttpResult.newSuccess().add("data",list).add("count",recordCount);

    }


}
